package org.nowcoder.leetcode.stack;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Title  : 150. Evaluate Reverse Polish Notation
 * Source : https://leetcode.cn/problems/evaluate-reverse-polish-notation/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-12
 */

public class LeetCode_150 {
    public int evalRPN(String[] tokens) {
        Deque<Integer> results = new ArrayDeque<>();
        for (String token : tokens) {
            switch (token) {
                case "+": {
                    if (results.size() > 1) {
                        int left = results.pop();
                        int right = results.pop();
                        results.push(left + right);
                    }
                    break;
                }
                case "-": {
                    if (results.size() > 1) {
                        int left = results.pop();
                        int right = results.pop();
                        results.push(right - left);
                    }
                    break;
                }
                case "*": {
                    if (results.size() > 1) {
                        int left = results.pop();
                        int right = results.pop();
                        results.push(left * right);
                    }
                    break;
                }
                case "/": {
                    if (results.size() > 1) {
                        int left = results.pop();
                        int right = results.pop();
                        results.push(right / left);
                    }
                    break;
                }
                default:
                    results.push(Integer.parseInt(token));
                    break;
            }
        }
        return results.isEmpty() ? 0 : results.peek();
    }
}
